<script setup lang="ts">
import { getPatientInfoByIdAPI, postPatientAddAPI, putPatientUpdateAPI } from '@/apis/patient'
import type { PostPatientAddParams } from '@/types/patient'
import { onLoad, onReady } from '@dcloudio/uni-app'
import { ref } from 'vue'

// 表单数据
const formData = ref<PostPatientAddParams>({
  name: '',
  idCard: '',
  gender: 1,
  defaultFlag: 0,
})

// 表单规则
const formRules = ref<UniHelper.UniFormsRules>({
  name: {
    rules: [
      { required: true, errorMessage: '请填写患者姓名' },
      { pattern: /^[\u4e00-\u9fa5]{2,5}$/, errorMessage: '请输入中文姓名' },
    ],
  },
  idCard: {
    rules: [
      { required: true, errorMessage: '请填写患者身份证号' },
      {
        pattern: /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[0-1])\d{3}(\d|X)$/,
        errorMessage: '请填写正确的身份证号',
      },
    ],
  },
  gender: {
    rules: [
      { required: true, errorMessage: '请选择患者性别' },
      {
        //自定义校验规则
        validateFunction: (rule, value, data, callback) => {
          // 判断身份证第 17 位(索引为16)是否与选择的性别一致
          if (Number(formData.value.idCard.charAt(16)) % 2 !== value) {
            // callback 处理提示错误信息
            callback('选择的性别与身份号中性别不一致')
          }
          // 如果身份证号第17位与选择的性别一致，则通过校验
          return true
        },
      },
    ],
  },
})

// Switch 开关组件切换事件
const onChangeDefaultFlag = (event: UniHelper.SwitchOnChangeEvent) => {
  formData.value.defaultFlag = event.detail.value ? 1 : 0
}

// 提交表单
const formRef = ref<UniHelper.UniFormsInstance>()
const onSubmit = async () => {
  //校验表单
  await formRef.value?.validate?.()
  // 如果页面参数有 id，调用编辑接口，否则调用添加接口
  if (props.id) {
    const { name, idCard, defaultFlag, id, gender } = formData.value
    // 编辑患者
    await putPatientUpdateAPI({ name, idCard, defaultFlag, id, gender })
  } else {
    // 调用接口，注意：一个帐号最多添加 6 个患者
    await postPatientAddAPI(formData.value)
  }

  //跳转回患者列表
  uni.navigateBack()
  //提示添加成功
  uni.showToast({title:props.id ? '编辑成功' : '添加成功',icon: 'success'})
}

//通过 onLoad 生命周期获取页面参数
onLoad((options) => {
  console.log('页面参数', options)
})

// 页面级组件，可通过 defineProps 获取页面参数
const props = defineProps<{ id: string }>()
console.log('页面参数', props)

// 动态设置导航栏标题
uni.setNavigationBarTitle({ title: props.id ? '编辑患者' : '添加患者' })

// 获取患者详情
const getPatientInfoById = async () => {
  if (props.id) {
    const res = await getPatientInfoByIdAPI(props.id)
    formData.value = res.data
  }
}

getPatientInfoById()
</script>

<template>
  <scroll-view>
    {{ formData }}
    <view class="archive-page">
      <uni-forms border label-width="220rpx" :model="formData" :rules="formRules" ref="formRef">
        <uni-forms-item label="患者姓名" name="name">
          <uni-easyinput
            v-model="formData.name"
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :input-border="false"
            :clearable="false"
            placeholder="请填写真实姓名"
          />
        </uni-forms-item>
        <uni-forms-item label="患者身份证号" name="idCard">
          <uni-easyinput
            v-model="formData.idCard"
            placeholder-style="color: #C3C3C5; font-size: 32rpx"
            :input-border="false"
            :clearable="false"
            placeholder="请填写身份证号"
          />
        </uni-forms-item>
        <uni-forms-item label="患者性别" name="gender">
          <uni-data-checkbox
            v-model="formData.gender"
            selectedColor="#16C2A3"
            :localdata="[
              { text: '男', value: 1 },
              { text: '女', value: 0 },
            ]"
          />
        </uni-forms-item>
        <uni-forms-item label="默认就诊人">
          <view class="uni-switch">
            <switch
              color="#20c6b2"
              style="transform: scale(0.7)"
              @change="onChangeDefaultFlag"
              :checked="formData.defaultFlag === 1"
            />
          </view>
        </uni-forms-item>
        <button class="uni-button" @tap="onSubmit">保存</button>
      </uni-forms>
    </view>
  </scroll-view>
</template>

<style lang="scss">
@import './index.scss';
</style>
